package tech.xiaozai.exam.security.authentication;

import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import tech.xiaozai.exam.mapper.SysUserMapper;
import tech.xiaozai.exam.mapper.SysUserRoleRelationMapper;
import tech.xiaozai.exam.po.SysUser;
import tech.xiaozai.exam.po.SysUserExample;
import tech.xiaozai.exam.po.SysUserRoleRelationExample;
import tech.xiaozai.exam.po.SysUserRoleRelationKey;
import tech.xiaozai.exam.security.MyGrantedAuthority;
import tech.xiaozai.exam.security.MyUserDetails;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-09-23 10:38
 */
public class MyUserDetailsService implements UserDetailsService {


    @Setter
    @Autowired
    private SysUserMapper userMapper;

    @Setter
    @Autowired
    private SysUserRoleRelationMapper userRoleRelationMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //第一段: 取用户
        SysUserExample example = new SysUserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<SysUser> sysUsers = userMapper.selectByExample(example);
        if(sysUsers==null || sysUsers.isEmpty()){
            throw new UsernameNotFoundException("用户名["+username+"]不存在");
        }
        SysUser user = sysUsers.get(0);


        //第二段: 取角色ID
        SysUserRoleRelationExample example2 = new SysUserRoleRelationExample();
        example2.createCriteria().andUidEqualTo(user.getId());
        List<SysUserRoleRelationKey> keys = userRoleRelationMapper.selectByExample(example2);
        //将该用户的角色id的字符串形式的集合放在UserDetails中
        Collection<GrantedAuthority> authorities = new LinkedHashSet<>();
        keys.forEach(key->{
            MyGrantedAuthority authority = new MyGrantedAuthority();
            authority.setAuthority(key.getRid().toString());
            authorities.add(authority);
        });

        return new MyUserDetails().setId(user.getId())
                .setPassword(user.getPassword())
                .setState(user.getState())
                .setUsername(user.getUsername())
                .setAuthorities(authorities);
    }
}
